package com.ksyun.ks3.services.handler;


import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSink;
import okio.ForwardingSource;
import okio.Okio;
import okio.Sink;
import okio.Source;

public class ProgressResponseBody extends ResponseBody {
    private ResponseBody responseBody;
    private BufferedSource bufferedSource;
    private AsyncHttpResponseHandler handler;

    public ProgressResponseBody(ResponseBody responseBody, AsyncHttpResponseHandler handler) {
        this.responseBody = responseBody;
        this.handler = handler;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (null == bufferedSource) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source (Source source) {
        return new ProgressBufferedSource(source);
    }

    private class ProgressBufferedSource extends ForwardingSource {

        private long totalBytesRead = 0l; // 合计读入的字节数
        public ProgressBufferedSource(Source source) {
            super(source);
        }

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long readLength = super.read(sink, byteCount);
            totalBytesRead += readLength > 0 ? readLength : 0;
            handler.onProgress(totalBytesRead, responseBody.contentLength());
            return readLength;
        }
    }

}
